package com.zte.claa.inficombo.csa.app.service.rptparse;

import org.json.JSONObject;

import com.zte.claa.inficombo.csa.app.comm.csif.CSIFCommService;
import com.zte.claa.inficombo.csa.app.model.dev.DevRunState;
import com.zte.claa.inficombo.csa.app.service.redis.PublishDataBuilder;
import com.zte.claa.inficombo.csa.app.util.JsonUtils;
import com.zte.claa.inficombo.csa.app.util.XEuiUtils;

public class ParserDevOnlineData extends ParserDefault {
	public static final String MSG_TYPE_V125 = "dev_online";
	public static final String MSG_TYPE_V126 = "dev_state_notify";
	
	public String getType() {
		return MSG_TYPE_V126;
	}
	
	/**
	 * 解析终端状态上报消息
	 * CSIFV1.2.5之前版本：
	 * {
		  "cmd": "dev_online",
		  "deveui": "2C26C50001FF0001",
		  "online": true
		}
		CSIFV1.2.6版本：
		{
		  "cmd": "dev_state_notify",
		  "deveui": "2C26C50001FF0001",
		  "state": "online"
		}
	 */
	public void parseData(String jsonData, CSIFCommService svr) throws Exception {
		if(jsonData == null || jsonData.trim().equals("")){
			return;
		}
		JSONObject json = new JSONObject(jsonData);
		String devEui = JsonUtils.getJsonAttrVal(json, "deveui", null);
		if(devEui == null){
			logger.warn("ParserDevOnlineData: deveui is null: "+jsonData);
			return;
		}
		// 1.解析消息.
		byte runState = DevRunState.RUNSTATE_UNKNOWN;
		devEui = XEuiUtils.appendStartZero4xEUI(devEui);
		String stateStr = JsonUtils.getJsonAttrVal(json, "state", null);
		if(stateStr != null){
			stateStr = stateStr.trim();
			if(stateStr.equalsIgnoreCase("online")){
				runState = DevRunState.RUNSTATE_ONLINE;
			}
			else if(stateStr.equalsIgnoreCase("offline")){
				runState = DevRunState.RUNSTATE_OFFLINE;
			}
		} 
		// 兼容1.2.5版本的消息接口.
		else {
			String online = JsonUtils.getJsonAttrVal(json, "online", null);
			if(online != null){
				boolean b = Boolean.parseBoolean(online);
				if(b){
					runState = DevRunState.RUNSTATE_ONLINE;
				} else {
					runState = DevRunState.RUNSTATE_OFFLINE;
				}
			}
		}
		DevRunState rs = new DevRunState();
		rs.setDevEUI(devEui);
		rs.setRunState(runState);
		
		// 2.持久化保存；
		this.container.getPersisService().updateDevRunState(rs, true);
		logger.debug("Update dev run state ok: "+jsonData);
		
		// 3.redis发布通知
		String jsonMsg = PublishDataBuilder.buildDevRunStateMsg(rs);
		this.container.getStatePublisher().publishMessage(jsonMsg);
		logger.info("Publish dev run state msg ok: "+jsonMsg);
	}
}
